import baseUrl from './base.js'

let token_str = 'F_TOKEN'

export const request = (url, method, params) => {
	let token = uni.getStorageSync('token')
	// console.log('token', token)
	return new Promise(resolve => {
		uni.request({
			url: baseUrl.url + url,
			timeout: 100000,
			method: method,
			data: params,
			header: {
				'content-type': 'application/json',
				'F_TOKEN': token
			},
			success: (res) => {
				resolve(res)
			},
			fail: (error) => {
				resolve(error)
			}
		})
	})
}

export const get = (data) => {
	let token = uni.getStorageSync('token')
	// console.log('token', token)
	return new Promise(resolve => {
		uni.request({
			url: baseUrl.url + data.url,
			timeout: 100000,
			method: 'GET',
			data: data.params,
			header: {
				'token': token
			},
			success: (res) => {
				// console.log('get res:', res)
				if (res && res.data.code === 401) {
					const launchOptions = uni.getLaunchOptionsSync();
					uni.showModal({
						title: '提示',
						content: '您还没有登录，请先登录!',
						success(res) {
							if (res.confirm) {
								uni.setStorageSync('login_return_page', launchOptions.path);
								// 重新登录
								uni.navigateTo({
									url: '/pages/login/index',
									success() {}
								});
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					})
					resolve()
				}
				resolve(res)
			},
			fail: (error) => {
				resolve(error)
			}
		})
	})
};
export const post = (data) => {
	let token = uni.getStorageSync('token')
	// console.log('token', token)
	return new Promise(resolve => {
		uni.request({
			url: baseUrl.url + data.url,
			timeout: 100000,
			method: 'POST',
			header: {
				'content-type': 'application/json',
				'token': token
			},
			data: data.params,
			success: (res) => {
				if (res && res.data.code === 401) {
					const launchOptions = uni.getLaunchOptionsSync();
					uni.showModal({
						title: '提示',
						content: '您还没有登录，请先登录!',
						success(res) {
							if (res.confirm) {
								uni.setStorageSync('login_return_page', launchOptions.path);
								// 重新登录
								uni.navigateTo({
									url: '/pages/login/index',
									success() {}
								});
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					})
					resolve()
				}
				return resolve(res)
			},
			fail: (error) => {
				return resolve(error)
			}
		})
	})
};
